package com.minelx.serverandclient.connector;

import com.minelx.serverandclient.stream.data.Packet;

import java.io.Closeable;
import java.io.IOException;

public class PacketTubes implements Closeable {

	private final ITubes tubes;

	private final PacketReader reader;

	private final PacketWriter writer;

	public PacketTubes(ITubes tubes) {
		this.tubes = tubes;
		reader = new PacketReader(tubes.in());
		writer = new PacketWriter(tubes.out());
	}

	public void send(Packet packet) {
		try {
			writer.writePacket(packet);
		} catch (IOException e) {
			throw new IllegalStateException("Toward connector has closed.");
		}
	}

	public Packet receive() {
		try {
			return reader.take();
		} catch (IOException e) {
			throw new IllegalStateException("Tube has closed.");
		}
	}

	@Override
	public void close() {
		tubes.closeAnyway();
	}
}
